package com.yequan.thread.deadlock;

import java.util.concurrent.*;

/**
 * @author yequan
 * @date 2019/12/03
 */
public class ThreadDeadLockTest {

    //创建一个阻塞队列
    private static BlockingQueue Q = new ArrayBlockingQueue(10);
    //线程池线程数量
    private static final int THREAD_SIZE = 2;

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        //创建一个固定线程的线程池
        ExecutorService service = Executors.newFixedThreadPool(THREAD_SIZE);
        service.submit(new Task1());
        service.submit(new Task2(1));
        service.shutdown();
    }

    //任务1取出阻塞队列的值并打印
    static class Task1 implements Callable {
        @Override
        public Object call() throws Exception {
            System.out.println("Task1 is running");
            //取出阻塞队列的值，如果没有则会阻塞
            int value = (int) Q.take();
            System.out.println("Task1 finished, value = " + value);
            return null;
        }
    }

    //任务2，往阻塞队列增加元素
    static class Task2 implements Callable {
        private int val;

        public Task2(int value) {
            val = value;
        }

        @Override
        public Object call() throws Exception {
            System.out.println("Task2 put value = " + val);
            //往阻塞队列增加元素
            Q.put(1);
            return null;
        }
    }


}
